<?php
require_once "db.php";
session_start();

$idproj = db_escape($_POST['proj_id']);
$proj_query_text = "SELECT movies_idmovies, halls_idhalls FROM projection WHERE idprojection = '$idproj'";
$proj_query = db_query($proj_query_text);
while ($proj_row = mysqli_fetch_assoc($proj_query)) {
	$idmovie = $proj_row['movies_idmovies'];
	$idhall = $proj_row['halls_idhalls'];
}

$hall_query_text = "SELECT num_of_rows, num_of_col, seats_on_upper_row, type FROM halls WHERE idhalls = '$idhall'";
$hall_query = db_query($hall_query_text);
while ($hall_row = mysqli_fetch_assoc($hall_query)) {
	$numrow = $hall_row['num_of_rows'];
	$numcol = $hall_row['num_of_col'];
	$upper_row = $hall_row['seats_on_upper_row'];
	$type_hall = $hall_row['type'];
}
$numseats = 0;
if ($type_hall == '0') {
	$numseats = $numrow*$numcol;
	for ($i=1; $i <=$numseats ; $i++) { 
		$key = 'seat'.$i;
		if (isset($_POST[$key])) {
			$abs_seat_number = db_escape($_POST[$key]);
			$row = floor($abs_seat_number/$numcol)+1;
			if ($abs_seat_number%$numcol==0) {
				$seat = $numcol;
			}
			else {
				$seat = $abs_seat_number%$numcol;
			}
			echo 'seat '.$seat.' numrow '.$row;
			$accid = $_SESSION['uid'];
			$reservation_query_text = "INSERT INTO reservations (row, seat, accounts_idaccounts, projection_idprojection, movies_idmovies) VALUES ('$row', '$seat', '$accid', '$idproj', '$idmovie')";
			$reservation_query = db_query($reservation_query_text);
		}
	}
}
elseif ($type_hall == '1') {
	for ($k=$upper_row; $k > $upper_row - $numrow; $k--) { 
		$numseats += $k;
	}  
	for ($i=0; $i <=$numseats; $i++) { 
		$key = 'seat'.$i;
		$checked = 0;
		if (isset($_POST[$key])) {
			$abs_seat_number = db_escape($_POST[$key]);
			for ($on_that_row = $upper_row, $j=$numrow; $j >= 1; $j--, $on_that_row--) { 
				if ($j == $numrow) {
					$cap = $numseats;
				}
				else{
					$cap = $numseats-$checked;
				}
				$checked += $on_that_row;
				$seat = 1;
				for ($l=$numseats-$checked+1; $l <= $cap; $l++, $seat++) { 
					if ($abs_seat_number==$l) {
						echo 'seat '.$seat.' numrow '.$j;
						$accid = $_SESSION['uid'];
						$reservation_query_text = "INSERT INTO reservations (row, seat, accounts_idaccounts, projection_idprojection, movies_idmovies) VALUES ('$j', '$seat', '$accid', '$idproj', '$idmovie')";
						$reservation_query = db_query($reservation_query_text);
					}
				}
			}
		}
	}
}
echo 'Your reservation is accepted.';


